package com.openbravo.data.loader.sentence.interceptor;

import com.openbravo.data.loader.dataset.DataResultSet;
import com.openbravo.data.loader.sentence.I_DBExecInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class ExecTimeInterceptor implements I_DBExecInterceptor {
    public static final Logger logger= LoggerFactory.getLogger(ExecTimeInterceptor.class);

    long startTime;

    long maxTime;

    public ExecTimeInterceptor() {
        this(0);
    }

    public ExecTimeInterceptor(long maxTime) {
        this.maxTime = maxTime;
    }

    @Override
    public String interceptorExecBefore(String sentenceSql) {

        startTime = System.currentTimeMillis();

        return sentenceSql;
    }

    @Override
    public Map.Entry<String, Object> interceptorExecPreparedBefore(final String sql, final Object paras) {

        startTime = System.currentTimeMillis();

        return new Map.Entry<String, Object>(){

            @Override
            public String getKey() {
                return sql;
            }

            @Override
            public Object getValue() {
                return paras;
            }

            @Override
            public Object setValue(Object value) {
                return null;
            }
        };
    }

    @Override
    public void interceptorAfter(DataResultSet dataResultSet) {
        long time=System.currentTimeMillis()-startTime;
        if(time>maxTime)
           logger.info("exec total time:{}ms",time);
    }
}
